package com.szh.mysobproject.ui.activity

import android.view.Gravity
import android.view.View
import android.webkit.CookieManager
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.lifecycle.MutableLiveData
import by.kirich1409.viewbindingdelegate.viewBinding
import com.hjq.base.BaseDialog
import com.hjq.widget.view.SwitchButton
import com.szh.mysobproject.R
import com.szh.mysobproject.aop.SingleClick
import com.szh.mysobproject.app.AppActivity
import com.szh.mysobproject.app.AppApplication
import com.szh.mysobproject.databinding.SettingActivityBinding
import com.szh.mysobproject.db.SobCacheManager
import com.szh.mysobproject.manager.*
import com.szh.mysobproject.other.AppConfig
import com.szh.mysobproject.ui.dialog.MenuDialog
import com.szh.mysobproject.ui.dialog.SelectDialog
import com.szh.mysobproject.ui.dialog.UpdateDialog
import com.szh.mysobproject.util.startActivity
import com.szh.mysobproject.model.AppUpdateInfo
import com.szh.mysobproject.viewmodel.UserViewModel
import com.szh.mysobproject.viewmodel.app.AppViewModel
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

/**
 * @author : create by  szh
 * @date : 2022/6/21 15:40
 * @desc :设置界面
 */

@AndroidEntryPoint
class SettingActivity : AppActivity(), SwitchButton.OnCheckedChangeListener {
    private val TAG = "SettingActivity"

    private val mBinding: SettingActivityBinding by viewBinding()
    private var isAutoCheckAppVersion = true
    private var mAppVersionLiveData = MutableLiveData<AppUpdateInfo?>()

    @Inject
    lateinit var mAppViewModel: AppViewModel
    private val mUserViewModel by viewModels<UserViewModel>()

    override fun getLayoutId(): Int = R.layout.setting_activity

    override fun initObserver() {
        mAppVersionLiveData.observe(this) { appUpdateInfo ->
            hideUpdateIcon()
            appUpdateInfo ?: run {
                if (isAutoCheckAppVersion.not()) {
                    toast(R.string.check_update_error)
                }
                return@observe
            }
            // 是否需要强制更新（当前版本低于最低版本，强制更新）
            val needForceUpdate = AppConfig.getVersionCode() < appUpdateInfo.minVersionCode
            if (needForceUpdate) {
                showUpdateIcon()
                showAppUpdateDialog(appUpdateInfo, true)
                return@observe
            }
            // 当前版本是否低于最新版本
            if (AppConfig.getVersionCode() < appUpdateInfo.versionCode) {
                showUpdateIcon()
                showAppUpdateDialog(appUpdateInfo, appUpdateInfo.forceUpdate)
            } else {
                if (isAutoCheckAppVersion.not()) {
                    toast("已经是最新版本")
                }
            }
        }
        mBinding.sbSettingCache.rightText = CacheDataManager.getTotalCacheSize(this)
    }

    private fun showAppUpdateDialog(appUpdateInfo: AppUpdateInfo, forceUpdateApp: Boolean) {
        UpdateDialog.Builder(this)
            .setFileMd5(appUpdateInfo.apkHash)
            .setDownloadUrl(appUpdateInfo.url)
            .setForceUpdate(forceUpdateApp)
            .setUpdateLog(appUpdateInfo.updateLog)
            .setVersionName(appUpdateInfo.versionName)
            .show()
    }


    override fun initView() {
        // 设置切换按钮的监听
        mBinding.sbSettingSwitch.setOnCheckedChangeListener(this)
        setOnClickListener(
            R.id.sb_setting_language,
            R.id.sb_setting_update,
            R.id.sb_setting_agreement,
            R.id.sb_setting_about,
            R.id.sb_setting_cache,
            R.id.sb_setting_auto,
            R.id.sb_setting_exit
        )
    }

    override fun initData() {
        // 获取应用缓存大小
        mBinding.sbSettingCache.rightText = CacheDataManager.getTotalCacheSize(this)
        mBinding.sbSettingLanguage.rightText = "简体中文"
        mBinding.sbSettingSwitch.isChecked = true

        //检查更新
        mAppViewModel.checkAppUpdate().observe(this) {
            isAutoCheckAppVersion = true
            mAppVersionLiveData.value = it.getOrNull()
        }
    }

    override fun initEvent() {
        mBinding.sbSettingCache.setOnLongClickListener {
            fun Int.isOpenAutoCleanCache() = this == 0
            fun Boolean.selectIndex() = if (this) 0 else 1
            // 选择清理模式
            SelectDialog.Builder(this)
                .setTitle("空闲时自动清理")
                .setList("开", "关")
                // 设置单选模式
                .setSingleSelect()
                // 设置默认选中
                .setSelect(AppManager.isAutoCleanCache().selectIndex())
                .setListener { _, data ->
                    // 单选
                    val keys = data.keys
                    if (keys.size == 1) {
                        val key = keys.toList()[0]
                        AppManager.setAutoCleanCache(key.isOpenAutoCleanCache())
                    }
                }
                .show()
            true
        }
    }

    @SingleClick
    override fun onClick(view: View) {
        when (view.id) {
            R.id.sb_setting_language -> {
                // 底部选择框
                MenuDialog.Builder(this) // 设置点击按钮后不关闭对话框
                    //.setAutoDismiss(false)
                    .setList(R.string.setting_language_simple, R.string.setting_language_complex)
                    .setListener(MenuDialog.OnListener { _: BaseDialog?, _: Int, string: String? ->
                        mBinding.sbSettingLanguage.rightText = string
                        BrowserActivity.start(
                            activity,
                            "https://github.com/getActivity/MultiLanguages"
                        )
                    })
                    .setGravity(Gravity.BOTTOM)
                    .setAnimStyle(BaseDialog.ANIM_BOTTOM)
                    .show()
            }
            R.id.sb_setting_update -> {
                // 检查更新
                mAppViewModel.checkAppUpdate().observe(this) {
                    isAutoCheckAppVersion = false
                    mAppVersionLiveData.value = it.getOrNull()
                }
            }
            R.id.sb_setting_agreement -> {
                BrowserActivity.start(activity, "https://t-dms.yili.com/upload/view.do?id=ff808081830af82d01830ba969862dca")
            }
            R.id.sb_setting_about -> {
                startActivity<AboutActivity>()
            }
            R.id.sb_setting_auto -> {
                // 自动登录
                val sbSettingSwitch = mBinding.sbSettingSwitch
                sbSettingSwitch.isChecked = !sbSettingSwitch.isChecked
            }
            R.id.sb_setting_cache -> {
                mAppViewModel.clearCacheMemory().observe(this) {
                    val totalCacheSize = it.getOrNull() ?: return@observe
                    mBinding.sbSettingCache.rightText = totalCacheSize
                }
            }
            R.id.sb_setting_exit -> {
                // 清除用户信息
                UserManager.exitUserAccount()
                // 清除 WebView 的 Cookie
                val cookieManager = CookieManager.getInstance()
                cookieManager.removeAllCookies(null)
                val database = AppApplication.getDatabase()
                val cookieDao = database.cookieDao()
                ThreadPoolManager.getInstance().execute() {
                    // 清除App本地缓存的 Cookie（必须在非主线程操作）
                    cookieDao.clearCookies()
                }

                mUserViewModel.logout().observe(this) {
                    SobCacheManager.onAccountLoginOut()
                    LoginActivity.start(this, "", "")
                    // 进行内存优化，销毁除登录页之外的所有界面
                    ActivityManager.getInstance().finishAllActivities(LoginActivity::class.java)
                }

            }
        }
    }

    /**
     * 隐藏更新提示图标
     */
    private fun hideUpdateIcon() {
        mBinding.tvSettingUpdate.isVisible = false
    }

    /**
     * 显示更新提示图标
     */
    private fun showUpdateIcon() {
        mBinding.tvSettingUpdate.isVisible = true
    }

    /**
     * [SwitchButton.OnCheckedChangeListener]
     */
    override fun onCheckedChanged(button: SwitchButton, checked: Boolean) {
        // TODO: 设置是否自动登录
//        UserManager.setupAutoLogin(checked)
//        ToastUtils.showShort("checked$checked")
    }

    override fun isStatusBarDarkFont(): Boolean {
        return false
    }
}